<template>
  <div>
    <div :loading="loading" class="app-container">
      <!--对象操作-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Back" @click="handleBack">
            返回
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Connection"
            @click="handleAddReqs"
            v-hasPermi="['tms:testplan:addReq']"
            >添加需求
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Connection"
            @click="handleAddCases"
            v-hasPermi="['tms:testplan:addCase']"
            >添加用例
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Tickets"
            @click="handleGenOutline"
            v-hasPermi="['tms:testplan:genReport']"
            >生成大纲
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Tickets"
            @click="handleGenReport"
            v-hasPermi="['tms:testplan:genReport']"
            >生成报告
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Edit"
            @click="handleEdit"
            v-hasPermi="['tms:testplan:edit']"
            >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            v-hasPermi="['tms:testplan:delete']"
            >删除
          </el-button>
        </el-col>

        <y-history-toolbar
          :prefix="form.prefix"
          :historys="historys"
          :command="handleCommand"
        />
      </el-row>

      <!-- 信息展示 -->
      <el-row :gutter="10">
        <!-- 左侧详情展示 -->
        <el-col :lg="16" :xs="24">
          <reqs-card ref="reqsCardRef" :testplan="id" title="需求信息" />
          <br />
          <cases-card ref="casesCardRef" :testplan="id" title="用例信息" />
        </el-col>

        <!-- 右侧属性展示 -->
        <el-col :lg="8" :xs="8">
          <el-card>
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本信息" name="1">
                <el-descriptions direction="vertical" :column="1" border>
                  <el-descriptions-item label="计划名称">{{
                    form.name
                  }}</el-descriptions-item>
                  <el-descriptions-item label="所属产品">
                    <router-link
                      v-if="form.product"
                      :to="'/pms/product-info/index/' + form.product.value"
                      class="link-type"
                    >
                      <span>{{ form.product.label }}</span>
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="影响版本">
                    <router-link
                      v-if="form.version"
                      :to="'/pms/version-info/index/' + form.version.value"
                      class="link-type"
                    >
                      <span>{{ form.version.label }}</span>
                    </router-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="计划开始时间">{{
                    form.scheduled_start
                  }}</el-descriptions-item>
                  <el-descriptions-item label="计划结束时间">{{
                    form.scheduled_end
                  }}</el-descriptions-item>
                  <el-descriptions-item label="实际开始时间">{{
                    form.actual_start
                  }}</el-descriptions-item>
                  <el-descriptions-item label="实际结束时间">{{
                    form.actual_end
                  }}</el-descriptions-item>
                  <el-descriptions-item label="创建人">{{
                    form.creator_name
                  }}</el-descriptions-item>
                  <el-descriptions-item label="创建时间">{{
                    form.create_time
                  }}</el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <y-dict-tag
                      :options="sys_enable_disable"
                      :value="form.status"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="标签">
                    <y-tag v-model="form.tags" :editable="false" />
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
            </el-tabs>
          </el-card>
          <br />
          <el-card>
            <div class="card-header">
              <h4><strong>操作记录</strong></h4>
            </div>
            <div class="card-body">
              <el-collapse>
                <el-collapse-item
                  v-for="record in form.history"
                  :title="record.title"
                >
                  <li v-for="sub in record.content">
                    {{ sub }}
                  </li>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改对话框 -->
    <au-plan
      :id="id"
      v-model="open"
      :title="title"
      :operate="operate"
      :getMethod="getTestPlan"
      :updateMethod="updateTestPlan"
      @submited="submited"
      @close="open = false"
    >
    </au-plan>

    <!-- 添加或修改需求对话框 -->
    <ad-reqs
      :id="id"
      v-model="openAdReqs"
      :title="title"
      :getMethod="getTestPlan"
      :updateMethod="updateTestPlan"
      @submited="submited"
      @close="openAdReqs = false"
    >
    </ad-reqs>

    <!-- 添加或修改用例对话框 -->
    <ad-cases
      :id="id"
      v-model="openAdCases"
      :title="title"
      :getMethod="getTestPlan"
      :updateMethod="updateTestPlan"
      @submited="submited"
      @close="openAdCases = false"
    >
    </ad-cases>

    <!-- 添加或修改报告对话框 -->
    <au-report
      :id="id"
      v-model="openAuReport"
      :title="title"
      :addMethod="addTestReport"
      @submited="submited"
      @close="openAuReport = false"
    >
    </au-report>

    <!-- 添加或修改用例对话框 -->
    <setting
      :id="id"
      v-model="openSetting"
      :title="title"
      @close="openSetting = false"
    >
    </setting>
  </div>
</template>

<script setup name="TestPlanInfo">
import {
  getTestPlan,
  getHistory,
  updateTestPlan,
  delTestPlan,
} from "@/api/tms/testplan";
import AuPlan from "./components/AuPlan";
import AdReqs from "./components/AdReqs";
import AdCases from "./components/AdCases";
import Setting from "./components/Setting";
import { addTestReport } from "@/api/tms/testreport";
import AuReport from "@/views/tms/testreport/components/AuReport";
import ReqsCard from "@/views/pms/requirement/components/ReqsCard";
import CasesCard from "@/views/tms/testcase/components/CasesCard";

const { proxy } = getCurrentInstance();
const { sys_enable_disable } = proxy.useDict("sys_enable_disable");

const id = proxy.$route.params.id;
const open = ref(false);
const title = ref("");
const loading = ref(false);
const operate = ref("update");
const activeName = ref("1");
const historys = ref([]);
const openAdReqs = ref(false);
const openAdCases = ref(false);
const openAuReport = ref(false);
const openSetting = ref(false);

const data = reactive({
  form: {},
});

const { form } = toRefs(data);

/** 获取计划详情 */
async function getInfo() {
  loading.value = true; // 开始加载
  try {
    const response = await getTestPlan(id);
    form.value = response.data;

    const historyResponse = await getHistory(id);
    historys.value = historyResponse.data;
  } catch (error) {
    console.error("Failed to fetch data:", error); // 错误处理
  } finally {
    loading.value = false; // 确保在最后关闭加载状态
  }
}

/** 查询某条历史记录 */
function handleCommand(command) {
  form.value = command;
}

/** 返回按钮操作 */
function handleBack() {
  proxy.$router.back();
}

/** 添加需求操作 */
function handleAddReqs() {
  openAdReqs.value = true;
  title.value = "添加需求";
}

/** 添加用例操作 */
function handleAddCases() {
  openAdCases.value = true;
  title.value = "添加用例";
}

/** 生成大纲操作 */
function handleGenOutline() {
  openSetting.value = true;
  title.value = "生成设置";
}

/** 生成报告操作 */
function handleGenReport() {
  openAuReport.value = true;
  title.value = "生成报告";
}

/** 修改操作 */
function handleEdit() {
  open.value = true;
  title.value = "修改计划";
}

/** 删除按钮操作 */
function handleDelete() {
  proxy.$modal
    .confirm('是否确认删除计划名称为"' + form.value.name + '"的数据项?')
    .then(() => {
      return delTestPlan(form.value.id);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      handleBack();
    })
    .catch(() => {});
}

/** 添加/修改对象后触发事件 */
async function submited() {
  try {
    // 假设 getInfo 是一个异步函数，用于获取或更新数据
    await getInfo();

    // 使用 Vue 的 nextTick 确保 DOM 更新完成后再执行后续操作
    await nextTick();

    // 直接调用抽象出的函数，不捕获 getList 的异常，因为 getList 内部已经处理了
    callGetListIfExists(proxy.$refs.reqsCardRef);
    callGetListIfExists(proxy.$refs.casesCardRef);
  } catch (error) {
    // 处理 submited 函数执行过程中出现的错误，但不包括 getList 的错误
    console.error(
      "Error in submited function (excluding getList errors):",
      error
    );
    // 在这里可以添加更多的错误处理逻辑，如通知用户、记录日志等
  }
}

/**
 * 检查 ref 是否存在并且其 getList 是一个函数，如果是，则调用它
 * 注意：这里不捕获 getList 的异常，因为假设 getList 内部已经处理了
 * @param {Object} ref - Vue 组件的引用
 */
function callGetListIfExists(ref) {
  if (ref && typeof ref.getList === "function") {
    // 直接调用 getList，不捕获异常
    ref.getList();
  }
}

onMounted(async () => {
  await getInfo();
});
</script>
